<template>
  <div>
    <el-container style="height: 696px; border: 1px solid #eee">
      <Left></Left>
      <el-container>
        <el-header style="text-align: right; font-size: 12px;width: 100%;">
          <Top></Top>
        </el-header>
        <el-main
          v-loading="loading"
          element-loading-text="文件正在上传导入数据库，请稍候..."
          element-loading-spinner="el-icon-loading"
          element-loading-background="rgba(0, 0, 0, 0.5)">
          <el-row>
            <el-col :span="24">
              <div class="grid-content bg-purple-dark">
                <b style="color: #606266;margin: 20px 30px;text-align: center;font-size: 20px;">添加学生</b>
              </div>
            </el-col>
          </el-row>
          <el-divider content-position="left"><i class="el-icon-s-unfold"></i>&nbsp;&nbsp;逐个添加</el-divider>
          <div style="width: 650px;margin: 0 150px; border: 1px solid #eee">
            <div style="margin: 10px 10px;margin-right: 80px;">
              <el-form :model="ruleForm" :rules="rules" ref="ruleForm" style="margin: 10px auto;" label-width="100px"
                       class="demo-ruleForm">
                <el-form-item label="姓名" prop="studentName">
                  <el-input v-model="ruleForm.studentName"></el-input>
                </el-form-item>
                <el-form-item label="学号" prop="studentNum">
                  <el-input v-model="ruleForm.studentNum"></el-input>
                </el-form-item>
                <el-form-item label="性别" prop="studentSex">
                  <el-radio v-model="ruleForm.studentSex" label="男">男</el-radio>
                  <el-radio v-model="ruleForm.studentSex" label="女">女</el-radio>
                </el-form-item>
                <el-form-item label="年龄" prop="studentAge">
                  <el-slider
                    v-model="ruleForm.studentAge"
                    show-input>
                  </el-slider>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="submitForm('ruleForm')">立即添加</el-button>
                  <el-button @click="resetForm('ruleForm')">重置</el-button>
                </el-form-item>
              </el-form>
            </div>
          </div>
          <el-divider content-position="left"><i class="el-icon-s-unfold"></i>&nbsp;&nbsp;批量导入</el-divider>
          <div style="width: 650px;margin: 0 150px; border: 1px solid #eee">
            <div style="margin: 10px 50px;">
              <el-upload
                class="upload-demo"
                ref="upload"
                name="file"
                :action="uploadUrl()"
                accept="application/vnd.ms-excel"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :on-success="fileuploadSuccess"
                :on-progress="fileUploading"
                :before-upload="beforeUpload"
                :file-list="fileList"
                :auto-upload="false">
                <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
                <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">导入数据库
                </el-button>
                <div style="margin-top: 10px" slot="tip" class="el-upload__tip">只能上传固定格式的xls文件
                  <i style="color: blue;cursor: pointer;" @click="downloadTemplate">下载模板</i>
                </div>
              </el-upload>
            </div>
          </div>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script>
import Left from '@/components/teacherSide/left'
import Top from '@/components/teacherSide/top'

export default {
  name: 'teacherAddStudent',
  data () {
    return {
      teacherId: '',
      loading: false,
      fileList: [],
      ruleForm: {
        studentName: '',
        studentNum: '',
        studentAge: 20,
        studentSex: ''
      },
      rules: {
        studentName: [
          {required: true, message: '请输入姓名', trigger: 'blur'},
          {min: 1, max: 5, message: '长度在 1 到 5 个字符', trigger: 'blur'}
        ],
        studentNum: [
          {required: true, message: '请输入学号', trigger: 'blur'},
          {min: 12, max: 12, message: '长度在 12 个字符', trigger: 'blur'}
        ]
      }
    }
  },
  created () {
    this.teacherId = JSON.parse(localStorage.getItem('teacher')).teacherId
  },
  methods: {
    // 下载xls模板
    downloadTemplate () {
      this.$axios({
        method: 'POST',
        url: 'http://localhost:8888/student/excel_down',
        responseType: 'blob'
      }).then(res => {
        if (!res) {
          return
        }
        const blob = new Blob([res.data])
        if (window.navigator && window.navigator.msSaveOrOpenBlob) {
          navigator.msSaveBlob(blob, 'import_student_template')
        } else {
          let u = window.URL.createObjectURL(res.data)
          let aLink = document.createElement('a')
          aLink.style.display = 'none'
          aLink.href = u
          aLink.setAttribute('download', 'import_student_template.xls')
          document.body.appendChild(aLink)
          aLink.click()
          document.body.removeChild(aLink)
          window.URL.revokeObjectURL(u)
        }
      }).catch(error => {
        throw error
      })
    },
    // 导入数据库的Excel的URL
    uploadUrl: function () {
      return (
        'http://localhost:8888/upload_studentInformation/' + this.teacherId
      )
    },
    // 文件上传成功时的钩子
    fileuploadSuccess () {
      this.loading = false
      this.$message({
        message: '恭喜你，文件上传成功',
        type: 'success'
      })
    },
    // 上传文件之前的钩子
    beforeUpload (file) {
      if (file.type !== 'application/vnd.ms-excel') {
        this.$message({
          message: '警告哦，只能上传固定格式的xls文件',
          type: 'warning'
        })
        return false
      }
      return true
    },
    // 文件上传时的钩子
    fileUploading () {
      this.loading = true
    },
    // 导入数据库
    submitUpload () {
      this.$refs.upload.submit()
    },
    // 文件列表移除文件时的钩子
    handleRemove (file, fileList) {
      console.log(file, fileList)
    },
    // 点击文件列表中已上传的文件时的钩子
    handlePreview (file) {
      console.log(file)
    },
    // 逐个添加学生
    submitForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$axios.post('http://localhost:8888/oneByOneSaveStudent/' + this.teacherId, this.ruleForm).then(res => {
            this.$message({
              message: '恭喜你，添加成功',
              type: 'success'
            })
          }).catch(err => {
            return Promise.reject(err)
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm (formName) {
      this.$refs[formName].resetFields()
    }
  },
  components: {
    Left,
    Top
  }
}
</script>

<style>
  .el-row {
    margin-bottom: 20px;

  &
  :last-child {
    margin-bottom: 0;
  }

  }
  .el-col {
    border-radius: 4px;
  }

  .bg-purple-dark {
    background: #cadcf5;
  }

  .bg-purple {
    background: #d3dce6;
  }

  .bg-purple-light {
    background: #e5e9f2;
  }

  .grid-content {
    border-radius: 4px;
    min-height: 36px;
  }

  .row-bg {
    padding: 10px 0;
    background-color: #f9fafc;
  }
</style>
<style>
  .el-header {
    background-color: #B3C0D1;
    color: #333;
    line-height: 60px;
  }

  .el-aside {
    color: #42b983;
  }
</style>
<style scoped>
  .router-link-active {
    text-decoration: none;
    color: yellow;
  }

  a {
    text-decoration: none;
    color: cadetblue;
  }
</style>
